/**
 * 微信原生HTTP请求封装
 * 基于wx.request API，简化配置与使用
 */
import { config } from '../../config.js'
import { useStore } from '@/ya/store';

// 环境配置
const isProd = process.env.NODE_ENV === 'production';
const { BASE_URL, API_PATH } = isProd ? config.prod : config.dev;
const baseUrl = BASE_URL + API_PATH;

// 默认配置
const DEFAULT_OPTIONS = {
  method: 'GET',
  header: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Accept': '*/*'
  },
  timeout: 8000,
  showLoading: true,
  loadingMsg: '加载中...',
  showError: true,
  auth: true
};

class Request {
  constructor() {
    // 拦截器存储
    this.interceptors = {
      request: [],
      response: []
    };
  }

  /**
   * 注册请求拦截器
   * @param {Function} handler - (config) => config
   */
  useRequestInterceptor(handler) {
    this.interceptors.request.push(handler);
  }

  /**
   * 注册响应拦截器
   * @param {Function} handler - (response) => response
   */
  useResponseInterceptor(handler) {
    this.interceptors.response.push(handler);
  }

  /**
   * 核心请求方法
   * @param {Object} options - 请求配置
   */
  request(options) {
    // 合并配置
    const config = { ...DEFAULT_OPTIONS, ...options };
    const { url, showLoading, loadingMsg } = config;

    // 显示loading
    if (showLoading) {
      wx.showLoading({ title: loadingMsg, mask: true });
    }

    // 执行请求拦截器
    this.interceptors.request.forEach(handler => {
      config = handler(config) || config;
    });

    return new Promise((resolve, reject) => {
      wx.request({
        ...config,
        url: baseUrl + url,
        success: (response) => {
          // 执行响应拦截器
          this.interceptors.response.forEach(handler => {
            response = handler(response) || response;
          });
          resolve(response.data);
        },
        fail: (error) => {
          this._handleError(error, config);
          reject(error);
        },
        complete: () => {
          // 隐藏loading
          if (showLoading) {
            wx.hideLoading();
          }
        }
      });
    });
  }

  /**
   * 错误处理
   * @param {Object} error - 错误对象
   * @param {Object} config - 请求配置
   */
  _handleError(error, config) {
    if (!config.showError) return;

    let errorMsg = '网络请求失败，请稍后重试';
    if (error.errMsg.includes('timeout')) {
      errorMsg = '请求超时，请稍后重试';
    } else if (error.statusCode) {
      const statusMap = {
        401: '登录状态已过期，请重新登录',
        403: '没有权限访问',
        404: '请求资源不存在',
        500: '服务器内部错误'
      };
      errorMsg = statusMap[error.statusCode] || `请求错误(${error.statusCode})`;
    }

    wx.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 2000
    });

    // 401错误处理
    if (error.statusCode === 401 && config.auth) {
      useStore('user').logout();
      wx.redirectTo({ url: '/pages/login' });
    }
  }

  // 快捷请求方法
  get(url, data = {}, options = {}) {
    return this.request({ ...options, url, data, method: 'GET' });
  }

  post(url, data = {}, options = {}) {
    return this.request({ ...options, url, data, method: 'POST' });
  }

  put(url, data = {}, options = {}) {
    return this.request({ ...options, url, data, method: 'PUT' });
  }

  delete(url, data = {}, options = {}) {
    return this.request({ ...options, url, data, method: 'DELETE' });
  }
}

// 创建实例并配置默认拦截器
const request = new Request();

// 请求拦截器：添加token
request.useRequestInterceptor(config => {
  if (config.auth) {
    const token = wx.getStorageSync('token');
    if (token) {
      config.header.Authorization = token;
    }
  }
  return config;
});

// 响应拦截器：处理业务逻辑错误
request.useResponseInterceptor(response => {
  const { data } = response;
  if (data && data.code !== 0) {
    wx.showToast({
      title: data.msg || '操作失败',
      icon: 'none'
    });
    // 可在这里统一处理特定错误码
    if (data.code === 401) {
      useStore('user').logout();
      wx.redirectTo({ url: '/pages/login' });
    }
  }
  return response;
});

export default request;